Completed
Push — development ( 8ac5b9...913816 )
by Nils
08:20
created

functions.js ➔ validateURL   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
/**
2
 * @file          functions.js
3
 * @author        Nils Laumaillé
4
 * @version       2.1.27
5
 * @copyright     (c) 2009-2017 Nils Laumaillé
6
 * @licensing     GNU AFFERO GPL 3.0
7
 * @link          http://www.teampass.net
8
 *
9
 * This library is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
 */
13
14
/**
15
*   Show or hide Loading animation GIF
16
**/
17
function LoadingPage(){
18
    if ( $("#div_loading").is(':visible') )
19
        $("#div_loading").hide();
20
    else
21
        $("#div_loading").show();
22
}
23
24
/**
25
*   Reload a page
26
**/
27
function RefreshPage(myform){
28
    document.forms[myform].submit();
29
}
30
31
/**
32
*   Add 1 hour to session duration
33
**/
34
function IncreaseSessionTime(message_end, message_wait, duration){
35
    duration = duration || 60;
36
    $("#main_info_box_text").html(message_wait);
37
    $("#main_info_box").show().position({
38
        my: "center",
39
        at: "center top+75",
40
        of: "#top"
41
    });
42
    $.post(
43
        "sources/main.queries.php",
44
        {
45
        type    : "increase_session_time",
46
        duration: parseInt(duration) * 60
47
        },
48
        function(data){
49
            if (data[0].new_value != "expired") {
50
                $("#main_info_box_text").html(message_end);
51
                setTimeout(function(){$("#main_info_box").effect( "fade", "slow" );}, 1000);
52
                $("#temps_restant").val(data[0].new_value);
53
                $("#date_end_session").val(data[0].new_value);
54
                $('#countdown').css("color","white");
55
                $("#div_increase_session_time").dialog("close");
56
            } else {
57
                document.location = "index.php?session=expired";
58
            }
59
        },
60
        "json"
61
    );
62
}
63
64
/**
65
*   Countdown before session expiration
66
**/
67
function countdown()
68
{
69
    var DayTill
70
    var theDay =  $('#temps_restant').val();
71
    var today = new Date(); //Create an Date Object that contains today's date.
72
    var second = Math.floor(theDay - (today.getTime()/1000));
73
    var minute = Math.floor(second/60); //Devide "second" into 60 to get the minute
74
    var hour = Math.floor(minute/60); //Devide "minute" into 60 to get the hour
75
    var CHour= hour % 24; //Correct hour, after devide into 24, the remainder deposits here.
76
    if (CHour<10) {
77
        CHour = "0" + CHour;
78
    }
79
    var CMinute= minute % 60; //Correct minute, after devide into 60, the remainder deposits here.
80
    if (CMinute<10) {
81
        CMinute = "0" + CMinute;
82
    }
83
    var CSecond= second % 60; //Correct second, after devide into 60, the remainder deposits here.
84
    if (CSecond<10) {
85
        CSecond = "0" + CSecond;
86
    }
87
    DayTill = CHour+":"+CMinute+":"+CSecond;
88
89
    //Avertir de la fin imminante de la session
90
    if ( DayTill == "00:01:00" ){
91
        $('#div_increase_session_time').dialog('open');
92
        $('#countdown').css("color","red");
93
    }
94
95
    // Manage end of session
96
    if ($("#temps_restant").val() != "" && DayTill <= "00:00:00" && $("#please_login").val() != 1) {
97
        $("#please_login").val("1");
98
        document.location = "index.php?session=expired";
99
    }
100
101
    //Rewrite the string to the correct information.
102
    if ($('#countdown')){
103
        $('#countdown').html(DayTill); //Make the particular form chart become "Daytill"
104
    }
105
106
    var counter = setTimeout("countdown()", 1000); //Create the timer "counter" that will automatic restart function countdown() again every second.
0 ignored issues
show
introduced by
Using setTimeout with a string argument to run code is slow and may pose a security risk. Consider using a function instead.
Loading history...
Unused Code introduced by
The variable counter seems to be never used. Consider removing it.
Loading history...
107
}
108
109
/**
110
*   Open a dialog
111
**/
112
function OpenDialog(id){
113
    $('#'+id).dialog('open');
114
}
115
116
/**
117
*   Toggle a DIV
118
**/
119
function toggleDiv(id){
120
    $('#'+id).slideToggle("slow");
121
    //specific case to not show upgrade alert
122
    if(id == "div_maintenance"){
123
        $.post(
124
            "sources/main.queries.php",
125
            {
126
            type    : "hide_maintenance"
127
            }
128
        );
129
    }
130
}
131
132
/**
133
*   Checks if value is an integer
134
**/
135
function isInteger(s) {
136
  return (s.toString().search(/^-?[0-9]+$/) == 0);
137
}
138
139
/**
140
*   Generate a random string
141
**/
142
function CreateRandomString(size,type){
143
    var chars = "";
144
145
    // CHoose what kind of string we want
146
    if ( type == "num" ) chars = "0123456789";
147
    else if ( type == "num_no_0" ) chars = "123456789";
148
    else if ( type == "alpha" ) chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
149
    else if ( type == "secure" ) chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz&#@;!+-$*%";
150
    else chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
151
152
    //generate it
153
    var randomstring = '';
154
    for (var i=0; i<size; i++) {
155
        var rnum = Math.floor(Math.random() * chars.length);
156
        randomstring += chars.substring(rnum,rnum+1);
157
    }
158
159
    //return
160
    return randomstring;
161
}
162
163
164
/**
165
*
166
**/
167
function unsanitizeString(string){
168
    if(string != "" && string != null){
169
        string = string.replace(/\\/g,'').replace(/&#92;/g,'\\');
170
    }
171
    return string;
172
}
173
174
/**
175
*   Clean up a string and delete any scripting tags
176
**/
177
function sanitizeString(string){
178
    if(string != "" && string != null){
179
        string = string.replace(/\\/g,'&#92;').replace(/"/g,"&quot;");
180
        string = string.replace(new RegExp('\\s*<script[^>]*>[\\s\\S]*?</script>\\s*','ig'),'');
181
    }
182
    return string;
183
}
184
185
/**
186
*   Send email
187
**/
188
function SendMail(cat, content, key, message){
189
    $.post(
190
        "sources/items.queries.php",
191
        {
192
            type    : "send_email",
193
            cat     : cat,
194
            content : content,
195
            key     : key
196
        },
197
        function(data){
198
            if (data[0].error !== undefined && data[0].error !== "") {
199
                message = data[0].message;
200
            }
201
            $("#div_dialog_message_text").html(message);
202
            $("#div_dialog_message").dialog("open");
203
        },
204
        "json"
205
    );
206
}
207
208
/**
209
*   Checks if email has expected format ([email protected])
210
**/
211
function IsValidEmail(email){
212
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
213
    return filter.test(email);
214
}
215
216
/**
217
*   Checks if URL has expected format
218
**/
219
function validateURL(textval) {
220
    //var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
221
    var urlregex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
222
    return urlregex.test(textval);
223
}
224
225
226
function split( val ) {
227
    return val.split( / \s*/ );
228
}
229
230
function extractLast( term ) {
231
    return split( term ).pop();
232
}
233
234
235
function store_error(message_error, dialog_div, text_div){
236
    //Store error in DB
237
    $.post(
238
        "sources/main.queries.php",
239
        {
240
            type    : "store_error",
241
            error   : escape(message_error)
242
        }
243
    );
244
    //Display
245
    $("#"+text_div).html("An error appears. Answer from Server cannot be parsed!<br />Returned data:<br />"+message_error);
246
    $("#"+dialog_div).dialog("open");
247
}
248
249
function aes_encrypt(text, key)
250
{
251
    return Aes.Ctr.encrypt(text, key, 256);
252
}
253
254
255
function aes_decrypt(text, key)
256
{
257
    return Aes.Ctr.decrypt(text, key, 256);
258
}
259
260
function prepareExchangedData(data, type, key)
261
{
262
    var jsonResult;
0 ignored issues
show
Unused Code introduced by
The variable jsonResult seems to be never used. Consider removing it.
Loading history...
263
    if (type == "decode") {
264
        if ($("#encryptClientServer").val() == 0) {
265
            try {
266
                return $.parseJSON(data);
267
            }
268
                catch (e) {
269
                console.log("Error: "+e);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
270
                jsonErrorHdl(e);
271
            };
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
272
        } else {
273
            try {
274
                return $.parseJSON(aes_decrypt(data, key));
275
            }
276
                catch (e) {
277
                console.log("Error: "+e);
278
                jsonErrorHdl(e);
279
            };
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
280
        }
281
    } else if (type == "encode") {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if type == "encode" is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
282
        if ($("#encryptClientServer").val() == 0) {
283
            return data;
284
        } else {
285
            return aes_encrypt(data, key);
286
        }
287
    }
288
}
289
290
function jsonErrorHdl(message)
291
{
292
    $("#div_dialog_message_text").html(message);
293
    $("#div_dialog_message").dialog("open");
294
    $("#items_path_var").html('<i class="fa fa-folder-open-o"></i>&nbsp;Error');
295
    $("#items_list_loader").hide();
296
    return false;
297
}
298
299
function displayMessage(textToDisplay)
300
{
301
    $("#main_info_box_text").html(textToDisplay);
302
    $("#main_info_box").show().position({
303
        my: "center",
304
        at: "center top+20",
305
        of: "#main_simple"
306
    });
307
    setTimeout(function(){$("#main_info_box").effect( "fade", "slow");}, 2000);
308
}
309
310
311
function blink(elem, times, speed, klass)
312
{
313
    if (times > 0 || times < 0) {
314
      if ($(elem).hasClass(klass))
315
         $(elem).removeClass(klass);
316
      else
317
         $(elem).addClass(klass);
318
     }
319
320
     clearTimeout(function() { blink(elem, times, speed, klass); });
321
322
     if (times > 0 || times < 0) {
323
       setTimeout(function() { blink(elem, times, speed, klass); }, speed);
324
       times-= .5;
325
     }
326
}